package com.glodon.paas.account.util.captcha1;
import java.io.InputStream;
import java.net.URL;
import java.awt.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.glodon.paas.exception.PaasServerExceptionFactory;

public class FontCache {
	static Logger logger = LoggerFactory.getLogger(FontCache.class);


	static Font defaultFont = null; 
 	/**
 	 * 
 	 * @param fontName arial
 	 * @param style
 	 * @param fontHeight
 	 * @return
 	 */
	public static Font getFont(String fontName, int fontStyle, int fontHeight){
		Font temp = null;
		// 获取系统字体
		try {
			temp =  new Font(fontName,Font.PLAIN, fontHeight);
		} catch (Exception e) {
			logger.info(e.getMessage(),e);
		}
		if(temp != null){
			return temp;
		}

		// 获取系统默认字体
		try {
			temp =  new Font(null,Font.PLAIN, fontHeight);				
		} catch (Exception e) {
			logger.info(e.getMessage(),e);
		}
		
		if(temp != null){
			return temp;
		}
		
		// 获取自带字体	
		temp = loadDefaultFount();
		if(temp == null){
			logger.error("not system font to used,加载不到系统字体");
			throw PaasServerExceptionFactory.systemException("no system font", null);
		}
		return temp.deriveFont(fontStyle, fontHeight);
	} 
	
	// 加载字体文件
	static Font loadDefaultFount() {
		if (defaultFont != null) {
			return defaultFont;
		}

		try {
			URL url = FontCache.class.getResource("arial.ttf");
			if (url == null) {
				return null;
			}
			InputStream input = url.openStream();
			defaultFont = Font.createFont(Font.TRUETYPE_FONT, input);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return defaultFont;
	}
}
